<template>
  <div class="report-task">
    <el-row class="header" type="flex" justify="space-between">
      <div>
        <span class="header-title">【ID{{ previewObj.id }}】{{ previewObj.title }}</span>
        <span class="overdue-text" v-if="previewObj.overdue === '逾期'">逾期</span>
      </div>
      <el-button v-if="previewObj.overdue !== '逾期' && isBelongToUser" type="primary" size="small" icon="el-icon-edit"
        @click="toChildTask(previewObj)">任务分解</el-button>
    </el-row>
    <el-row :gutter="10" class="content">
      <el-col class="content-left" :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
        <el-tabs v-model="activeName">
          <el-tab-pane v-if="previewObj.issued_superior !== -1 && previewObj.is_approval" name="dealWithSign">
            <span slot="label"><i class="el-icon-message"></i> 处理签</span>
            <pager :isReportTask="true" :pager="previewObj"></pager>
          </el-tab-pane>
          <el-tab-pane name="baseInfo">
            <span slot="label"><i class="el-icon-date"></i> 详情信息</span>
            <div class="contcontent-left-des" v-html="previewObj.body"></div>
            <div class="fileList" v-if="hasTaskFile">
              <div class="text">附件</div>
              <div class="items">
                <div class="item" v-for="(item,index) in previewObj.taskFile" :key="index">
                    <image-type :width="20" :fileType="item.fileType"></image-type>
                    <!-- <img :src="require('@/assets/images/'+ fileFilter(item.fileType) +'.png')" alt="" class="file-img"> -->
                    <span class="name" @click="previewFile(item)">{{ item.name }}</span>
                    <!-- <div class="toolBox">
                      <el-button type="text" >在线阅读</el-button>
                      <el-button type="text" @click="previewImage(item.url)">下载</el-button> 
                    </div> -->
                </div>
              </div>
            </div>
            <!-- 通知类型任务反馈 -->
            <task-info-feedback
              v-if="previewObj.overdue !== '逾期' && noticeType !== 'other' && !isComplementTask"
              :noticeType="noticeType"
              :taskId="previewObj.id"
              @onSubmit="fetchCompleTask"
            />
            <div class="fileUpload-history" v-if="previewObj.data_type === '文件上传'">
              <div class="title" v-if="historyFileNum">
                <i class="el-icon-paperclip"></i>
                <span class="name">已上传文件记录</span>
              </div>
              <history-file ref="historyFile" :taskId="previewObj.id" @setHistoryFileNum="getHistoryFileNum"></history-file>
            </div>

            <div class="table-model">
              <TableInfo ref="tableInfo" :taskId="taskid" :preview="true" :isFinish="previewObj.is_finish"  :initTableHeader="previewObj.form_data"
                v-if="previewObj.data_type === '表格填报'"></TableInfo>
            </div>
            <el-row v-if="!previewObj.is_finish" type="flex" justify="end" class="btngroup">
              <el-button type="primary" size="small" icon="el-icon-upload"
                v-if="previewObj.data_type === '表格填报'"
                :disabled="previewObj.overdue === '逾期' || !isBelongToUser || !previewObj.is_publish"
                @click="handleReportTask(previewObj.id)">提交</el-button>
              <el-button type="primary" size="small" icon="el-icon-upload" v-if="previewObj.data_type === '文件上传'"
                :disabled="previewObj.overdue === '逾期' || !isBelongToUser || !previewObj.is_publish" @click="clickUp">
                上报文件</el-button>
              <el-button type="primary" size="small" icon="el-icon-upload" v-if="previewObj.data_type === '测评问卷'"
                :disabled="previewObj.overdue === '逾期' || !isBelongToUser || !previewObj.is_publish"
                @click="dialogQuestionVisible = true">填写问卷</el-button>
            </el-row>
          </el-tab-pane>
          <el-tab-pane name="taskIndex" v-if="previewObj.data_type === '文件上传' && previewObj.target">
            <span slot="label"><i class="el-icon-coordinate"></i> 任务指标</span>
            <RelateTarget ref="targetInfo" v-if="previewObj.target" :isMark="true" :isShow="true"
              :target="previewObj.target" :isOverdue="previewObj.overdue === '逾期'" />
          </el-tab-pane>
          <el-tab-pane name="subTask">
            <span slot="label"><i class="el-icon-medal"></i> {{ taskSize }}</span>
            <el-table :data="previewObj.child" stripe style="width: 100%;">
              <el-table-column prop="id" label="ID" min-width="80"></el-table-column>
              <el-table-column prop="title" label="任务名称" min-width="280" align="left">
                <template slot-scope="{ row, $index}">
                    <span class="subTask" @click="linkToDetail(row.id)">{{ row.title }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="data_type" label="上报类别" min-width="90"></el-table-column>
              <el-table-column prop="classify_name" label="任务类别" min-width="90"></el-table-column>
              <el-table-column prop="emergency_level" label="紧急程度" min-width="90"></el-table-column>
              <el-table-column label="截至日期" min-width="180">
                <template slot-scope="{row}">
                  <span>{{ parseTime(row.end_time) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col class="content-right" :xs="24" :sm="24" :md="24" :lg="6" :xl="6" v-if="isShowBaseInfo">
        <div class="desc">基本信息</div>
        <el-form ref="form" label-width="90px" class="baseinfo">
          <el-form-item label="任务名称">
            {{previewObj.title || '- -'}}
          </el-form-item>
          <el-form-item label="任务类别"> {{previewObj.classify_name || '- -'}}</el-form-item>
          <el-form-item label="上报类别"> {{previewObj.data_type || '- -'}}</el-form-item>
          <el-form-item label="紧急程度">
            <el-tag :type="previewObj.emergency_level | tagType">
              {{ previewObj.emergency_level }}
            </el-tag>
          </el-form-item>
          <el-form-item label="截止时间"> {{ parseTime(previewObj.end_time) }}</el-form-item>
          <el-form-item label="创建人"> {{previewObj.owner}}</el-form-item>
          <el-form-item label="创建时间"> {{ parseTime(previewObj.create_time) }}</el-form-item>
          <el-form-item label="发布状态">
            <el-tag :type="previewObj.status | tagType">
              {{ previewObj.status }}
            </el-tag>
          </el-form-item>
          <el-form-item v-if="isBelongToUser" label="是否完成" >
            <el-switch disabled v-model="previewObj.is_finish"
              @click.native="changeTaskStatus"></el-switch>
          </el-form-item>

        </el-form>
      </el-col>
    </el-row>
    <div class="fileup-wrapper">
      <el-dialog width="660px" title="上报文件" :visible.sync="dialogFormVisible">
        <file-upload ref="upload" :params="uploadParam" postUrl="/api/Work/File/" @uploadFile="handFinishUpload"></file-upload>
      </el-dialog>

    </div>
    <div class="question-wrapper">
      <el-dialog width="960px" title="填写问卷" :visible.sync="dialogQuestionVisible">
        <QuestionRecord :taskId="taskid" :preview="false" :isSuperior="previewObj.issued_superior > 0" :initQuestionInfo="previewObj.question_data" v-if="previewObj.data_type === '测评问卷'"></QuestionRecord>
      </el-dialog>
    </div>

  </div>
</template>
<script>
  import {
    mapGetters
  } from 'vuex'
  
  import _ from 'lodash'
  import {
    postCreateTask,
    getModels,
    getTaskInfo,
    updateTaskPart
  } from '@/api/work.js'
  import {
    completeTasks
  } from '@/api/workflow.js'
  import {
    getTable,
    getQuestion
  } from '@/api/question.js'
  import {
    parseTime,
    getFileType
  } from '@/utils/index.js'

  import axios from 'axios'
  import Cookies from 'js-cookie'
  import store from '@/store'

  export default {
    name: 'taskCenter',
    components: {
      'TableInfo': require('@/views/markSys/taskCenter/showRecord/components/TableInfo.vue').default,
      'QuestionRecord': require('@/views/markSys/questionRecord/index.vue').default,
      'ImageType': () => import('@/components/ImageType'),
      'FileUpload': () => import("@/components/FileUpload"),
      'RelateTarget': () => import("../../components/relateTarget"),
      'Pager': () => import("../../approve/handler/Pager"),
      'HistoryFile': () => import('./components/historyFile'),
      'TaskInfoFeedback': () => import("../../components/TaskInfoFeedback"),
    },
    data() {
      return {
        previewObj: {},
        activeName: 'baseInfo',
        historyFileNum: 0, // 历史上传文件数量
        uploadParam: {},
        queryData: {}, // 路由参数
        dialogFormVisible: false,
        dialogQuestionVisible: false,
        taskid: null,
        processId: null
      }
    },
    computed: {
      hasTaskFile() {
        return this.previewObj.taskFile && !!this.previewObj.taskFile.length
      },
      isShowBaseInfo() {
        const width = document.documentElement.clientWidth
        if (width < 1200) {
          if (this.activeName === 'baseInfo') return true
          return false
        }
        return true
      },
      // 返回通知对应任务类型
      noticeType() {
        const { classify_name, data_type } = this.previewObj
        if(data_type === '通知') {
          return classify_name
        }
        return 'other'
      },
      // 返回任务是否完成
      isComplementTask() {
        return this.previewObj.is_finish
      },
      taskSize() {
        const size = this.previewObj.child && this.previewObj.child.length
        return '子任务(' + size + ')'
      },
      ...mapGetters([
        'name',
        'id'
      ]),
      isBelongToUser() {
        if (this.previewObj && this.previewObj.user) {
          return this.previewObj.user.includes(Number(this.id))
        }
      }
    },
    watch: {
      dialogFormVisible(val) {
        if (!val) {
          this.$refs.upload.clear();
        }
      }
    },
    created() {
      this.queryData = this.$route.params
      if(!this.queryData.targetId){
        this.$router.push({name: 'HomePage'})
        return
      }
      // const id = this.$route.params && this.$route.params.id
      // this.processId = this.$route.query && this.$route.query.processId

      this.taskid = this.queryData.targetId + ''
      this.fetchData(this.taskid)

    },
    methods: {
      parseTime,
      // 返回历史上传文件记录数量
      getHistoryFileNum(num) {
        this.historyFileNum = num
      },
      // 跳转到创建子任务 
      toChildTask(row) {
        this.$router.push({
          name: 'CreateTask',
          params: {
            parent: row.id,
            initData: row
          }
        })
      },
      // 完成任务开关
      changeTaskStatus(val) {
        if(this.previewObj.overdue === '逾期' || this.previewObj.is_finish || this.previewObj.id === 1326) return
        this.$confirm('选择更改任务为完成状态后将不可以取消, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {  
            this.fetchCompleTask()
          })
      },
      // 提交完成任务请求
      fetchCompleTask(joinParam) {
        const param = {
          dealReason: '',
          dealType: '0',
          dealUserId: this.id,
          dealUserName: this.name,
          dealUnitId: "0",
          businessKey: this.taskid
        }
        // 如果为会议通知类型，添加参与信息
        if(joinParam && ~joinParam.status.indexOf('参与')) {
          const { status, content = '' } = joinParam
          param.isJoin = status 
          param.joinReson = content 
        }
        completeTasks(this.queryData.id, param).then(
            r =>{
              if(r && r.data && r.data.code === '200'){
                updateTaskPart(this.taskid, {
                  is_finish: this.previewObj.is_finish
                }).then(
                  res => {
                    if (res && res.data && res.data.id) {
                      this.$notify({
                        title: '提示',
                        message: '任务状态已更改为完成',
                        type: 'success'
                      });
                      this.previewObj.is_finish = true
                    }
                  }
                )
              }else{
                this.$notify({
                        title: '提示',
                        message: '任务状态更改失败',
                        type: 'error'
                      });
              }
            }
          )
      },
      fetchData(id) {
        // 获取基础填信息
        getTaskInfo(id).then(res => {
          this.previewObj = res.data
          this.formatData(this.previewObj)
        })
      },
      // 跳转到在线office页面
      previewFile(row) {
        const { id, fileType, url } = row
        const canPreviewOnlyOffice = [ 'doc', 'docx' ,'wps', 'xls', 'xlsx', 'pptx']
        if(["bmp", "png", "gif", "jpeg", "jpg", "mp4", "mp3", 'pdf', "json", "txt", "js"].includes(fileType)){
          this.previewImage(url)
        }else if(canPreviewOnlyOffice.includes(fileType)) {
          const { href } = this.$router.resolve({
            name:'FilePreview',
            query: {
              fileId: id,
              previewType: 0
            }
          })
          window.open(href, '_blank')
        }else {
          this.$message.info(`所选文件暂不支持在线预览`);
        }
      },
      // 预览图片
      previewImage(url) {
        window.open(url, '_blank')
      },
      // 编辑任务
      handleReportTask:_.throttle(
        function(index){
       if (this.previewObj.data_type === '表格填报') {
          const isGreat = this.previewObj.issued_superior > 0
          this.$refs['tableInfo'].postTable(isGreat)
        }
      }, 4000,{ 'trailing': false }),

       
      // 点击上传
      clickUp() {
        if (this.previewObj.target) {
          // 跳转到关联指标痕迹
          // this.$router.push({
          //   path: `/index-manager/checkIndex/${this.previewObj.target}`
          // })
          this.activeName = 'taskIndex'
        } else {
          this.dialogFormVisible = true
          this.uploadParam = {
            task: this.taskid,
            obj: 'task',
            owner: store.getters.id,
          };
        }
      },
      /**
      * 上传完成时关闭对话框，刷新数据
      */
      handFinishUpload() {
        this.dialogFormVisible = false;
        this.$refs.upload.clear();
        this.$refs.historyFile.fetchHistoryFile();
      },
      // 跳转到任务详情
      linkToDetail(id){
        this.$router.push({
          name: 'PreviewTask',
          params: {
            targetId: id,
          }
        })
      },
      formatData(obj) {
        const res = []
        obj.status = obj.is_publish ? '已发布' : '未发布'
        obj.taskFile.forEach(e => {
          res.push({
            id: e.id,
            name: this.formatFile(e.url),
            url: process.env.VUE_APP_IMAGE_URL + '/upload/' + e.url,
            fileType: getFileType(e.url, '.')
          })
        })
        obj.taskFile = res
        return obj
      },
      formatFile(str) {
        const file = getFileType(str, '/')
        return decodeURI(file)
      }
    },
  }

</script>
<style lang="scss">
  .report-task {
    .header {
      padding: 10px 18px;
      // border-bottom: 1px solid #ddd;
      font-size: 18px;
      font-weight: 600;
      line-height: 2;
      align-items: baseline;

      .overdue-text {
        display: inline-block;
        height: 19px;
        line-height: 19px;
        vertical-align: text-top;
        font-size: 12px;
        color: #fff;
        background: #ff6060;
        border-radius: 4px;
        padding: 1px 3px;
      }
    }

    .content {
      padding: 5px 0;

      &-right {
        // border-left: 1px solid #ccc;
      }

      &-left {
        min-height: 355px;
        padding: 0 20px;

        .btngroup {
          margin-top: 10px;
        }

        .fileList {
          display: flex;
          border-top: 1px solid #f1f1f1;
          margin-top: 26px;

          .text {
            padding: 12px 0;
          }

          .items {
            margin-left: 20px;

            .item {
              display: flex;

              .name {
                padding: 12px 0;
                max-width: 500px;
                overflow: hidden;
                font-size: 14px;
                line-height: 16px;
                color: #808080;
                text-overflow: ellipsis;
                cursor: pointer;
                &:hover {
                  color: #409eff
                }
              }

              .toolBox {
                color: #6f6f6f;
                margin-left: 20px;
                opacity: 0;
              }

              &:hover {
                .toolBox {
                  opacity: 1;
                }
              }
            }
          }
        }

        .subTask {
          color: #409eff;
          cursor: pointer;
        }

        .fileUpload-history {
          .title {
            color: #409eff;

            .name {
              line-height: 20px;
              display: inline-block;
              list-style: none;
              font-size: 14px;
              font-weight: 500;
            }
          }
        }
      }

      &-right {
        .desc {
          padding: 10px 20px;
        }

        .baseinfo {
          padding: 0 20px;
        }
      }

      .fileup-wrapper {
        .content {
          /* width: 300px;
        height: 80px; */
          margin-bottom: 20px;
          background: #fff;

          .text {
            text-align: center;
            padding: 10px 0;
          }
        }
      }
    }

    .report-wraper {
      .file-model {
        padding: 4px;
        background: #e0e0e0;
        /* border: 1px solid #ccc;
            border-radius: 6px; */
        display: flex;

        >span {
          min-width: 50px;
          font-size: 18px;
          line-height: 1.5;
          font-weight: bold;
        }

        .filtList {
          padding: 2px 0;
          margin: 0 8px;
          border-bottom: 1px solid #409eff;

          >span {
            color: #409eff;
          }

          .toolBox {
            text-align: center;

            .el-button {
              padding: 0;
            }
          }
        }
      }
    }

    .el-form-item {
      margin: 0;
    }

    .el-form-item__label {
      text-align: left;
      font-size: 13px;
      color: #909090;
      font-weight: normal;
    }

    .el-form-item__content {
      font-size: 13px;
      word-break: break-all;
      word-wrap: break-word;
    }

    .el-tabs {
      margin: 0 20px;
    }

    .el-tabs__content {
      padding: 0 15px;
    }

    .el-tabs__nav-scroll {
      padding: 0 15px;
    }

    .el-tabs__item {
      height: 43px !important;
    }

    .el-divider--horizontal {
      margin: 15px 0;
    }
  }

</style>
<style>

</style>
